package hu.mapro.model.generator;

import hu.mapro.model.descriptor.Model;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.sun.codemodel.JClassAlreadyExistsException;
import com.sun.codemodel.JClassContainer;
import com.sun.codemodel.JCodeModel;

public class GeneratorUtil {

	public static Model getModel(InputStream is) {
		try {
			JAXBContext jc = JAXBContext.newInstance("hu.mapro.model.descriptor");
			Unmarshaller u = jc.createUnmarshaller();
			Model o = (Model) u.unmarshal(is);
			return o;
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	public static void generate(
			Model model, 
			File existingTargetDirectory,
			Generator generator
	) {
		try {
			JCodeModel cm = new JCodeModel();

			JClassContainer classContainer;

			if (model.getTargetClass() != null) {
				classContainer = cm._class(model.getTargetClass());
			} else {
				classContainer = cm._package(model.getTargetPackage());
			}

			generator.generate(model.getGenerate(), classContainer);

			cm.build(existingTargetDirectory);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (JClassAlreadyExistsException e) {
			throw new RuntimeException(e);
		}
	}

}
